package com.matt.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.matt.domain.Children;
import com.matt.domain.ChildrenHealthBaseInfo;
import com.matt.domain.Classes;
import com.matt.domain.LeaveRecord;
import com.matt.domain.care.*;
import com.matt.domain.course.Course;
import com.matt.domain.observation.ObservationNewRecord;
import com.matt.domain.record.CheckRecord;
import com.matt.domain.record.ChildrenLiveRecord;
import com.matt.domain.record.LiveRecord;
import com.matt.foundation.DO.course.CoursePlanClassesDDO;
import com.matt.foundation.utils.DateUtil;
import com.matt.foundation.utils.HttpClientUtil;
import com.matt.repository.ChildrenRepository;
import com.matt.repository.ClassesRepository;
import com.matt.repository.base.CoursePlanClassesNativeRepository;
import com.matt.repository.course.CourseRepository;
import com.matt.repository.rel.ChildrenLiveRecordRepository;
import com.matt.service.WxPushService;
import com.matt.service.care.po.HLHandoverRecordMedicinePO;
import com.matt.service.remoteCall.SsoCallService;
import com.tuo51.evaluate.domain.evaluatingV2.EvaluateV2Record;
import lombok.extern.slf4j.Slf4j;
//import net.sf.json.JSONArray;
//import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

//import com.matt.domain.evaluatingV2.EvaluateV2Record;


@Service
@Slf4j
public class WxPushServiceImpl implements WxPushService {


    @Value("${wx.post.url}")
    private  String wxPostUrl;

    @Value("${wx.push.link.url}")
    private  String wxPushLinkUrl;

    @Value("${wx.evaluaterecord.templateId}")
    private String evaluateRecordTemplateId;

    @Value("${wx.liverecord.templateId}")
    private String liveRecordTemplateId;

    @Value("${wx.checkin.templateId}")
    private String checkInTemplateId;

    @Value("${wx.checkout.templateId}")
    private String checkOutTemplateId;
    @Value("${wx.renew.templateId}")
    private String renewTemplateId;

    @Value("${wx.leave.record.templateId}")
    private String wxLeaveRecordTemplateId;

    @Value("${wx.observation.templateId}")
    private String observationTemplateId;

    @Value("${wx.dietinfo.templateId}")
    private String dietInfoTemplateId;

    @Value("${wx.emergency.templateId}")
    private String emergencyTemplateId;

    @Value("${wx.takemedicine.templateId}")
    private String takeMedicineTemplateId;

    @Value("${wx.dailyinfo.templateId}")
    private String dailyInfoTemplateId;

    @Value("${wx.weekreport.templateId}")
    private String weekReportTemplateId;

    @Value("${wx.payorder.notify.templateId}")
    private String payOrderNotifyTemplateId;

    @Value("${wx.payorder.result.templateId}")
    private String payOrderResultTemplateId;

//    @Value("${pc.internet.domain.url}")
//    private String pcDomainUrl;
//
//    @Value("${api.internet.domain.url}")
//    private String appDomainUrl;

    @Value("${wx.push.channel}")
    private String pushChannel;


    @Autowired
    private ChildrenRepository childrenRepository;

    @Autowired
    private ClassesRepository classesRepository ;

    @Autowired
    private ChildrenLiveRecordRepository childrenLiveRecordRepository;

    @Autowired
    private CoursePlanClassesNativeRepository coursePlanClassesNativeRepository ;

    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private SsoCallService ssoCallService;

    private JSONObject jsonKeyword(String name, String value){
        return jsonKeyword(name, value, "#743A3A");
    }

    private JSONObject jsonKeyword(String name, String value, String color){
        JSONObject keyword1 = new JSONObject();
        keyword1.put("name", name);
        keyword1.put("value", value);
        keyword1.put("color", color);
        return keyword1;
    }

    @Override
    @Async
    public  void pushEvaluateRecordV2(EvaluateV2Record evaluateRecord, String toUserOpenId ){
        String childrenId = evaluateRecord.getChildrenId();

        // FIXME:  这个url要替换
            String jumpUrl = wxPushLinkUrl +"/#/evaluatePsycal?evaluateRecordId=" + evaluateRecord.getId();
        String templateId = evaluateRecordTemplateId;
        Children children = childrenRepository.getOne(childrenId);

        Date evaluateRecordDate = evaluateRecord.getCreated();
        Calendar cal = Calendar.getInstance();
        cal.setTime(evaluateRecordDate);
        int evaluateRecordMonth = cal.get(Calendar.MONTH)+1; //注意月份是从0开始的

        String firstText = "您的宝宝"+evaluateRecordMonth+"月份心理行为测评已经发布!";
        String evaluateRecordDateStr = DateUtil.parseToDate(evaluateRecordDate);

        JSONObject keyword1 = new JSONObject();
        keyword1.put("name", "keyword1");
        keyword1.put("value", children.getName());
        keyword1.put("color", "#743A3A");

        JSONObject keyword2 = new JSONObject();
        keyword2.put("name", "keyword2");
        keyword2.put("value", "心理行为测评");
        keyword2.put("color", "#743A3A");

        JSONObject keyword3 = new JSONObject();
        keyword3.put("name", "keyword3");
        keyword3.put("value", evaluateRecord.getAdvise());
        keyword3.put("color", "#743A3A");

        JSONObject keyword4 = new JSONObject();
        keyword4.put("name", "keyword4");
        keyword4.put("value", evaluateRecordDateStr);
        keyword4.put("color", "#743A3A");


        JSONObject item_first = new JSONObject();
        item_first.put("name", "first");
        item_first.put("value", firstText);
        item_first.put("color", "#743A3A");

        JSONObject item_remark = new JSONObject();
        item_remark.put("name", "remark");
        item_remark.put("value", "");
        item_remark.put("color", "#743A3A");
        JSONArray arry = new JSONArray();

        arry.add(keyword1);
        arry.add(keyword2);
        arry.add(keyword3);
        arry.add(keyword4);
        arry.add(item_remark);
        arry.add(item_first);

        doWxTemplatePush(templateId, jumpUrl, arry.toString(), childrenId);
    }


    @Override
    @Async
    public void pushChildrenHealthRecord(ChildrenHealthBaseInfo record,String toUserOpenId) {
        String childrenId = record.getChildrenId();
//        String jumpUrl = wxPostUrl +"/babyReport.html?id="+record.getId();

        String jumpUrl = wxPushLinkUrl +"/#/health?id="+record.getId();

        String templateId = evaluateRecordTemplateId;
        Children children = childrenRepository.getOne(childrenId);

        Date recordDate = record.getCreated();
        Calendar cal = Calendar.getInstance();
        cal.setTime(recordDate);
        int evaluateRecordMonth = cal.get(Calendar.MONTH)+1; //注意月份是从0开始的

        String firstText = "您的宝宝"+evaluateRecordMonth+"月份儿保健康评测已经发布!";
        String evaluateRecordDateStr = DateUtil.parseToDate(recordDate);

        JSONObject keyword1 = new JSONObject();
        keyword1.put("name", "keyword1");
        keyword1.put("value", children.getName());
        keyword1.put("color", "#743A3A");

        JSONObject keyword2 = new JSONObject();
        keyword2.put("name", "keyword2");
        keyword2.put("value", "儿保评测");
        keyword2.put("color", "#743A3A");

        JSONObject keyword3 = new JSONObject();
        keyword3.put("name", "keyword3");
        keyword3.put("value", firstText);
        keyword3.put("color", "#743A3A");

        JSONObject keyword4 = new JSONObject();
        keyword4.put("name", "keyword4");
        keyword4.put("value", evaluateRecordDateStr);
        keyword4.put("color", "#743A3A");


        JSONObject item_first = new JSONObject();
        item_first.put("name", "first");
        item_first.put("value", "");
        item_first.put("color", "#743A3A");

        JSONObject item_remark = new JSONObject();
        item_remark.put("name", "remark");
        item_remark.put("value", "");
        item_remark.put("color", "#743A3A");
        JSONArray arry = new JSONArray();


        arry.add(keyword1);
        arry.add(keyword2);
        arry.add(keyword3);
        arry.add(keyword4);
        arry.add(item_remark);
        arry.add(item_first);

        doWxTemplatePush(templateId, jumpUrl, arry.toString(), childrenId);
    }

    @Override
    @Async
    public void pushLiveRecord(LiveRecord record,String toUserOpenId) {
//        String jumpUrl = wxPostUrl +"/babyDynamic.html";
        String jumpUrl = wxPushLinkUrl +"/#/dynamic?id="+record.getId();
        String templateId = liveRecordTemplateId;
        String liveRecordTitle = record.getTitle();
        String liveRecordId = record.getId();
        String dateStr = DateUtil.parseToDate(record.getCreated());
        List<ChildrenLiveRecord> relChildrenLiveRecords = childrenLiveRecordRepository.findByLiveRecordId(liveRecordId);

        for(ChildrenLiveRecord rel : relChildrenLiveRecords){
           String childrenId = rel.getChildrenId();
            Children children = childrenRepository.getOne(childrenId);

            JSONObject item_first = new JSONObject();
            item_first.put("name", "first");
            item_first.put("value", children.getName()+"的活动观察报告已经发布");
            item_first.put("color", "#743A3A");


            JSONObject keyword1 = new JSONObject();
            keyword1.put("name", "keyword1");
            keyword1.put("value", liveRecordTitle);
            keyword1.put("color", "#743A3A");

            JSONObject keyword2 = new JSONObject();
            keyword2.put("name", "keyword2");
            keyword2.put("value",dateStr);
            keyword2.put("color", "#743A3A");

            JSONObject keyword3 = new JSONObject();
            keyword3.put("name", "keyword3");
            keyword3.put("value", children.getName());
            keyword3.put("color", "#743A3A");



            JSONObject item_remark = new JSONObject();
            item_remark.put("name", "remark");
            item_remark.put("value", "点击【详情】可以查看详细的观察报告");
            item_remark.put("color", "#743A3A");
            JSONArray arry = new JSONArray();

            arry.add(keyword1);
            arry.add(keyword2);
            arry.add(keyword3);
            arry.add(item_remark);
            arry.add(item_first);

            doWxTemplatePush(templateId, jumpUrl, arry.toString(), childrenId);
        }
    }

    @Override
    @Async
    public void pushCheckInRecord(CheckRecord record,String toUserOpenId) {
        String childrenId = record.getChildrenId();
        Children children = childrenRepository.getOne(childrenId);
        int checkStatus = record.getStatus();//签到状态 0:缺席,1:入园,2:离园,3:拒绝入园,4:请假
        int healthyStatus = record.getHealthyStatus();//健康状态 0，健康，1，不健康
        String fistText ="【温馨提示】您的宝宝"+children.getName()+"今日已安全入园";
        if(checkStatus == 0){
            fistText ="【温馨提示】您的宝宝"+children.getName()+"今日缺席";
        }
        if(checkStatus == 1){
            fistText ="【温馨提示】您的宝宝"+children.getName()+"今日已安全入园";
        }

        if(checkStatus == 3){
            fistText ="【温馨提示】您的宝宝"+children.getName()+"今日被拒绝入园";
        }

        if(checkStatus == 4){
            fistText ="【温馨提示】您的宝宝"+children.getName()+"今日已请假";
        }

        String today = DateUtil.formatDayToStr(new Date());
//        String jumpUrl = wxPostUrl + "/#/checkin?date="+today;

        String jumpUrl = wxPushLinkUrl + String.format("/#/checkin?date=%s&childrenId=%s", today, childrenId);

        String templateId = checkInTemplateId;
        String dateStr = DateUtil.formatDateToStr(new Date());


        JSONObject item_first = new JSONObject();
        item_first.put("name", "first");
        item_first.put("value", fistText);
        item_first.put("color", "#743A3A");

        JSONObject keyword1 = new JSONObject();
        keyword1.put("name", "thing1");
        keyword1.put("value", children.getName());
        keyword1.put("color", "#743A3A");

        JSONObject keyword2 = new JSONObject();
        keyword2.put("name", "time2");
        keyword2.put("value",dateStr);
        keyword2.put("color", "#743A3A");

        JSONObject item_remark = new JSONObject();
        item_remark.put("name", "remark");
        item_remark.put("value", "若有疑问，请即时联系幼儿园！");
        item_remark.put("color", "#743A3A");
        JSONArray arry = new JSONArray();

        arry.add(keyword1);
        arry.add(keyword2);
        arry.add(item_remark);
        arry.add(item_first);

        doWxTemplatePush(templateId, jumpUrl, arry.toString(), childrenId);
    }

    @Override
    @Async
    public void pushCheckOutRecord(String childrenId,String toUserOpenId) {
        String today = DateUtil.formatDayToStr(new Date());
        String jumpUrl = wxPushLinkUrl + String.format("/#/checkin?date=%s&childrenId=%s", today, childrenId);
        String templateId = checkOutTemplateId;
        String dateStr = DateUtil.formatDateToStr(new Date());
        Children children = childrenRepository.getOne(childrenId);

        JSONObject item_first = new JSONObject();
        item_first.put("name", "first");
        item_first.put("value", "【温馨提示】您的宝宝已离园！");
        item_first.put("color", "#743A3A");

        JSONObject keyword1 = new JSONObject();
        keyword1.put("name", "thing1");
        keyword1.put("value", children.getName());
        keyword1.put("color", "#743A3A");

        JSONObject keyword2 = new JSONObject();
        keyword2.put("name", "time2");
        keyword2.put("value",dateStr);
        keyword2.put("color", "#743A3A");

        JSONObject item_remark = new JSONObject();
        item_remark.put("name", "remark");
        item_remark.put("value", "若有疑问，请即时联系幼儿园！");
        item_remark.put("color", "#743A3A");
        JSONArray arry = new JSONArray();

        arry.add(keyword1);
        arry.add(keyword2);
        arry.add(item_remark);
        arry.add(item_first);

        doWxTemplatePush(templateId, jumpUrl, arry.toString(), childrenId);
    }

    @Override
    @Async
    public void pushLeaveRecord(LeaveRecord leaveRecord, String toUserOpenId){
        String childrenId = leaveRecord.getChildrenId();
        String reason = leaveRecord.getContent();

        String today = DateUtil.formatDayToStr(new Date());
        String jumpUrl = null;
        String templateId = wxLeaveRecordTemplateId;
        String dateStr = DateUtil.parseToDateDay(leaveRecord.getLeaveDate());
        String dayType = "全天";
        if(leaveRecord.getLeaveType() == 1){
            dayType = "上午";
        }else if(leaveRecord.getLeaveType() == 2){
            dayType = "下午";
        }

        Children children = childrenRepository.getOne(childrenId);

//        亲爱的家长，您的宝宝请假已被批准！
//        宝贝姓名：XX
//        请假理由：XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX。
//        请假时间：XXXX年XX月XX日

//        {{first.DATA}} 请假人：{{keyword1.DATA}} 请假时间：{{keyword2.DATA}} 请假事由：{{keyword3.DATA}} {{remark.DATA}}

        JSONObject item_first =  (leaveRecord.getStatus() == 1)
                ? jsonKeyword("first", "亲爱的家长，您宝宝的请假已被批准！")
                : jsonKeyword("first", "亲爱的家长，您宝宝的请假已被拒绝！", "#FF0000");

        JSONObject keyword1 = jsonKeyword("keyword1", children.getName());

        JSONObject keyword2 = jsonKeyword("keyword2", dateStr + " "+ dayType);

        JSONObject keyword3 = jsonKeyword("keyword3", reason);

        JSONObject item_remark = jsonKeyword("remark", "若有疑问，请即时联系幼儿园！" );

        JSONArray arry = new JSONArray();

        JSONObject[] keys = {
                item_first,
                keyword1,
                keyword2,
                keyword3,
                item_remark
        };

        arry.addAll(Arrays.asList(keys));

        doWxTemplatePush(templateId, jumpUrl, arry.toString(), childrenId);
    }

    @Override
    @Async
    public void pushObservationNewRecord(String staffName, ObservationNewRecord record,String toUserOpenId) {
        pushObservationNewRecord(staffName, record, toUserOpenId, null);
    }

    @Async
    public void pushObservationNewRecord(String staffName, ObservationNewRecord record,String toUserOpenId, String feedid){
        String jumpUrl = wxPushLinkUrl +"/#/observation?id=" + (StringUtils.isEmpty(feedid) ? record.getId() : feedid);
        String templateId = observationTemplateId;
        String dateStr = DateUtil.parseToDate(new Date());
        Children children = childrenRepository.getOne(record.getChildrenId());
        String planId = record.getCoursePlanClassesId();
//        String teacherId = record.getTeacherId();
//        StaffDTO staffDTO = ssoCallService.getStaffDTOById(teacherId);
//        String teacherName = staffDTO.getRealName();
        CoursePlanClassesDDO coursePlanClasses = coursePlanClassesNativeRepository.findByCoursePlanClassesId(planId);
        String courseId = coursePlanClasses.getCourseId();

        Course course = courseRepository.getOne(courseId);
        String childrenId = record.getChildrenId();

        JSONObject item_first = new JSONObject();
        item_first.put("name", "first");
        item_first.put("value", "亲爱的家长，"+children.getName()+"宝贝上课的观察报告已生成！");
        item_first.put("color", "#743A3A");

        JSONObject keyword1 = new JSONObject();
        keyword1.put("name", "keyword1");
        keyword1.put("value", course.getName());
        keyword1.put("color", "#743A3A");

        JSONObject keyword2 = new JSONObject();
        keyword2.put("name", "keyword2");
        keyword2.put("value", staffName);
        keyword2.put("color", "#743A3A");

        JSONObject keyword3 = new JSONObject();
        keyword3.put("name", "keyword3");
        keyword3.put("value",dateStr);
        keyword3.put("color", "#743A3A");

        JSONObject item_remark = new JSONObject();
        item_remark.put("name", "remark");
        item_remark.put("value", children.getName()+"宝贝最新观测点报告新鲜出炉啦，老师都竖起了大拇指，继续加油！~ 快点击详情查看具体内容吧~");
        item_remark.put("color", "#743A3A");
        JSONArray arry = new JSONArray();

        arry.add(keyword1);
        arry.add(keyword2);
        arry.add(keyword3);
        arry.add(item_remark);
        arry.add(item_first);

        doWxTemplatePush(templateId, jumpUrl, arry.toString(), childrenId);
    }

//    @Override
//    public void pushEmergencyRecord(EmergencyRecord record, String toUserOpenId) {
//        //推送通知给微信用户
//        String jumpUrl ="";
//        String templateId = dailyInfoTemplateId;
//        String dateStr = DateUtil.parseToDate(new Date());
//        Children children = childrenRepository.getOne(record.getChildrenId());
//        String classesId = record.getClassesId();
//        String className = classesRepository.getOne(classesId).getName();
//        String childrenId = record.getChildrenId();
//
//
////        {{first.DATA}}
////        班级：{{keyword1.DATA}}
////        时间：{{keyword2.DATA}}
////        今日情况：{{keyword3.DATA}}
////        {{remark.DATA}}
//
//        JSONObject item_first = jsonKeyword("first", "亲爱的家长，"+children.getName()+"宝贝在园出现紧急情况！", "#FF0000" );
//
//        JSONObject keyword1 = jsonKeyword("keyword1", className);
//
//        JSONObject keyword2 = jsonKeyword("keyword2", dateStr);
//
//        JSONObject keyword3 = jsonKeyword("keyword3", record.getContent(), "#FF0000");
//
//        JSONObject item_remark = jsonKeyword("remark", "若有疑问，请即时联系幼儿园！" );
//
//        JSONArray arry = new JSONArray();
//        arry.add(keyword1);
//        arry.add(keyword2);
//        arry.add(keyword3);
//        arry.add(item_remark);
//        arry.add(item_first);
//
//        doWxTemplatePush(templateId, jumpUrl, arry.toString(), childrenId);
//    }
//
//    @Override
//    public void pushHospitalRecord(HospitalRecord record, String toUserOpenId) {
//        String jumpUrl ="";
//        String templateId = dailyInfoTemplateId;
//        String dateStr = DateUtil.parseToDate(record.getHospitalizedTime());
//
//        String childrenId = record.getChildId();
//        Classes classes = classesRepository.findByChildrenId(childrenId);
//
//        String className = classes.getName();
//
//
////        {{first.DATA}}
////        班级：{{keyword1.DATA}}
////        时间：{{keyword2.DATA}}
////        今日情况：{{keyword3.DATA}}
////        {{remark.DATA}}
//
//        JSONObject item_first = jsonKeyword("first", "亲爱的家长，"+ record.getChildName() + "宝贝有一条新的送医记录！", "#FF0000" );
//
//        JSONObject keyword1 = jsonKeyword("keyword1", className);
//
//        JSONObject keyword2 = jsonKeyword("keyword2", dateStr);
//
//        JSONObject keyword3 = jsonKeyword("keyword3", "送医", "#FF0000");
//
//        String remarkStr = "";
//        if(StringUtils.isNotEmpty(record.getHospitalName())){
//            remarkStr += (remarkStr.length()>0?"，":"") + "医院名称：" + record.getHospitalName();
//        }
//
//        if(record.getHospitalizedReason() != null && record.getHospitalizedReason() >= 0 && record.getHospitalizedReason() <= 8){
//            String[] preloadReasons = {"高烧","流血皮肤类外伤","骨折类","心脏疾病类","五官受伤","急性哮喘类","皮肤烫伤类","急性腹泻", "其他"};
//
//            String reasonStr = preloadReasons[record.getHospitalizedReason()];
//            if(record.getHospitalizedReason() == 8){
//                reasonStr = record.getReasonContent();
//            }
//
//            remarkStr += (remarkStr.length()>0?"，":"") + "送医原因：" + reasonStr;
//        }
//
//        if(StringUtils.isNotEmpty(record.getHospitalizedResult())){
//            remarkStr += (remarkStr.length()>0?"，":"") + "就医结论：" + record.getHospitalizedResult();
//        }
//
//        remarkStr += (remarkStr.length()>0?"，":"") + "请及时联系幼儿园！";
//
//        JSONObject remark = jsonKeyword("remark", remarkStr, "#FF0000");
//
//        JSONArray arry = new JSONArray();
//
//        arry.add(keyword1);
//        arry.add(keyword2);
//        arry.add(keyword3);
//        arry.add(remark);
//        arry.add(item_first);
//
//        doWxTemplatePush(templateId, jumpUrl, arry.toString(), childrenId);
//    }
//
    @Override
    @Async
    public void pushMedicalHandoverRecord(HLHandoverRecord record, String toUserOpenId) {
        String jumpUrl ="";
        String templateId = dailyInfoTemplateId;
        String dateStr = DateUtil.parseToDate(record.getEventTime());

        String childrenId = record.getChildId();
        Classes classes = classesRepository.findByChildrenId(childrenId);

        String className = classes.getName();


//        {{first.DATA}}
//        班级：{{keyword1.DATA}}
//        时间：{{keyword2.DATA}}
//        今日情况：{{keyword3.DATA}}
//        {{remark.DATA}}

        JSONObject item_first = jsonKeyword("first", "亲爱的家长，"+ record.getChildName() + "宝贝有一条新的药品交接记录！");

        JSONObject keyword1 = jsonKeyword("keyword1", className);

        JSONObject keyword2 = jsonKeyword("keyword2", dateStr);

        JSONObject keyword3 = jsonKeyword("keyword3", "药品交接");

        String remarkStr = "";
        if(record.getMedicines() != null && record.getMedicines().size() > 0){

            List t = record.getMedicines();
            List<HLHandoverRecordMedicinePO> mds = (List<HLHandoverRecordMedicinePO>)t;

            String medicineNames = null;

            if (t.get(0) instanceof HLHandoverRecordMedicine ){
                medicineNames = record.getMedicines().stream().map(o->o.getName()).collect(Collectors.joining("，"));
            }else{
                medicineNames = mds.stream().map(o->o.getName()).collect(Collectors.joining("，"));
            }



            remarkStr += (remarkStr.length()>0?"，\n":"") + "药品名称：" + medicineNames;
        }

        if(StringUtils.isNotEmpty(record.getGuardian())){
            remarkStr += (remarkStr.length()>0?"，\n":"") + "送药人：" + record.getGuardian();
        }

        remarkStr += (remarkStr.length()>0?"，":"") + "若有疑问，请及时联系幼儿园！";

        JSONObject remark = jsonKeyword("remark", remarkStr);

        JSONArray arry = new JSONArray();
        arry.add(keyword1);
        arry.add(keyword2);
        arry.add(keyword3);
        arry.add(remark);
        arry.add(item_first);

        doWxTemplatePush(templateId, jumpUrl, arry.toString(), childrenId);
    }

    @Override
    @Async
    public void pushTakeMedicalRecord(HLMedicationRecord record, String toUserOpenId){

        String childrenId = record.getChildId();
        String chilerenName = record.getChildName();

        String jumpUrl = "";

        //{{first.DATA}}
        //孩子姓名：{{keyword1.DATA}}
        //服药时间：{{keyword2.DATA}}
        //{{remark.DATA}}
        String templateId = takeMedicineTemplateId;
        if(StringUtils.isBlank(templateId)){
            return;
        }

        JSONObject item_first = jsonKeyword("first", "【温馨提示】亲爱的家长，你的孩子"+chilerenName+"宝贝已按时服药，请家长放心");

        String createDateStr = DateUtil.parseToDate(record.getEventTime());

        JSONObject keyword1 = jsonKeyword("keyword1", chilerenName);

        JSONObject keyword2 = jsonKeyword("keyword2", createDateStr);

        String remarkStr = "";
        if(StringUtils.isNotEmpty(record.getDrugName())){
            remarkStr += (remarkStr.length()>0?"，":"") + "药品名称：" + record.getDrugName();
        }
        if(StringUtils.isNotEmpty(record.getDrugPerson())){
            remarkStr += (remarkStr.length()>0?"，":"") + "喂药人：" + record.getCreatedBy();
        }

        String drugReaction = "";

        if(record.getReaction() != null)
            switch (record.getReaction()){
            //0:哭闹不停 1:平静 2:开心 3:过敏'
                case 0: {
                    drugReaction = "哭闹不停";
                }
                break;
                case 1:{
                    drugReaction = "平静";
                }
                break;
                case 2:{
                    drugReaction = "开心";
                }
                break;
                case 3:{
                    drugReaction = "过敏";
                }
                break;
            }
        if(StringUtils.isNotEmpty(drugReaction)){
            remarkStr += (remarkStr.length()>0?"，":"") + "服药后反应 ：" + drugReaction;
        }

        remarkStr += (remarkStr.length()>0?"，":"") + "若有疑问，请及时联系幼儿园！";

        JSONObject item_remark = jsonKeyword("remark", remarkStr);

        JSONArray arry = new JSONArray();
        arry.add(keyword1);
        arry.add(keyword2);
        arry.add(item_remark);
        arry.add(item_first);

        doWxTemplatePush(templateId, jumpUrl, arry.toString(), childrenId);
    }

    @Override
    @Async
    public void pushDietRecord(HLFeedingRecord record, String toUserOpenId) {
        String childrenId = record.getChildId();
        String chilerenName = record.getChildName();

        //{{first.DATA}}
        //取餐详情：{{keyword1.DATA}}
        //取餐时间：{{keyword2.DATA}}
        //{{remark.DATA}}
        String templateId = dietInfoTemplateId;
        if(StringUtils.isBlank(templateId)){
            return;
        }

        Date createDate = record.getEventTime();

        JSONObject item_first = jsonKeyword( "first" , "【温馨提示】亲爱的家长，你的孩子"+chilerenName+"宝贝有一条新的饮食记录");

        //String firstText = "您的宝宝"+chilerenName+"XXXX!";
        String createDateStr = DateUtil.parseToDate(createDate);

        JSONObject keyword1 = jsonKeyword("keyword1", record.getFood() + "  " + record.getQuantity());

        JSONObject keyword2 = jsonKeyword("keyword2", createDateStr);

        JSONObject item_remark = jsonKeyword("remark", "若有疑问，请及时联系幼儿园！");

        JSONArray arry = new JSONArray();
        arry.add(keyword1);
        arry.add(keyword2);
        arry.add(item_remark);
        arry.add(item_first);

        String jumpUrl = "";

        doWxTemplatePush(templateId, jumpUrl, arry.toString(), childrenId);
    }

    @Override
    @Async
    public void pushDefecationRecord(HLPottyRecord record, String toUserOpenId) {
        String jumpUrl ="";
        String templateId = dailyInfoTemplateId;
        String dateStr = DateUtil.parseToDate(record.getEventTime());

        String childrenId = record.getChildId();
        Classes classes = classesRepository.findByChildrenId(childrenId);

        String className = classes.getName();

        JSONObject item_first = jsonKeyword("first", "亲爱的家长，"+ record.getChildName() + "宝贝有一条新的大小便记录！");

        JSONObject keyword1 = jsonKeyword("keyword1", className);

        JSONObject keyword2 = jsonKeyword("keyword2", dateStr);

        String type =  record.getTypeStr();
        JSONObject keyword3 = jsonKeyword("keyword3", type);

        String remarkStr = "";
        if(record.getDiarrhea()){
            remarkStr += (remarkStr.length()>0?"，":"") + "有腹痛腹泻";
        }
        if(record.getMonkeyAss()){
            remarkStr += (remarkStr.length()>0?"，":"") + "有红屁屁";
        }

        if(StringUtils.isNotEmpty(record.getRemark())){
            remarkStr += (remarkStr.length()>0?"，":"") + record.getRemark();
        }

        remarkStr += (remarkStr.length()>0?"，":"") + "若有疑问，请及时联系幼儿园！";

        JSONObject remark = jsonKeyword("remark", remarkStr);

        JSONArray arry = new JSONArray();

        arry.add(keyword1);
        arry.add(keyword2);
        arry.add(keyword3);
        arry.add(remark);
        arry.add(item_first);

        doWxTemplatePush(templateId, jumpUrl, arry.toString(), childrenId);
    }

    @Override
    @Async
    public void pushWeekReportRecord(String childrenId, String childrenName, Date createDate, String content, String photos, String toUserOpenId) {
        //{{first.DATA}}
        //姓名：{{keyword1.DATA}}
        //班级：{{keyword2.DATA}}
        //学习评价：{{keyword3.DATA}}
        //{{remark.DATA}}


        Classes classes = classesRepository.findByChildrenId(childrenId);
        String className = classes.getName();

        String templateId = weekReportTemplateId;
        if(StringUtils.isBlank(templateId)){
            return;
        }

        JSONObject item_first = jsonKeyword( "first" , "【温馨提示】亲爱的家长，这是您宝贝的本周报告。");

        //String firstText = "您的宝宝"+chilerenName+"XXXX!";
        String createDateStr = DateUtil.parseToDate(createDate);

        JSONObject keyword1 = jsonKeyword("keyword1", childrenName);

        JSONObject keyword2 = jsonKeyword("keyword2", className);

        JSONObject keyword3 = jsonKeyword("keyword3", content);

        JSONObject item_remark = jsonKeyword("remark", "若有疑问，请及时联系幼儿园！");

        JSONArray arry = new JSONArray();
        arry.add(keyword1);
        arry.add(keyword2);
        arry.add(keyword3);
        arry.add(item_remark);
        arry.add(item_first);


        String jumpUrl = "";
        if(StringUtils.isNotBlank(photos)){
            jumpUrl = wxPushLinkUrl + "`/static/img_h5.html?img=" + photos;
        }

        doWxTemplatePush(templateId, jumpUrl, arry.toString(), childrenId);
    }

    @Override
    @Async
    public void pushRecipeReport(String areaId, String childrenId, String childrenName, String teacherName, String startDate, String endDate){
        Classes classes = classesRepository.findByChildrenId(childrenId);
        if(classes == null){
            return;
        }
        String className = classes.getName();

        String templateId = dailyInfoTemplateId;
        if(StringUtils.isBlank(templateId)){
            return;
        }

//        {{first.DATA}}
//        班级：{{keyword1.DATA}}
//        时间：{{keyword2.DATA}}
//        今日情况：{{keyword3.DATA}}
//        {{remark.DATA}}

        String content = teacherName + "老师发布了新的食谱。";
        String timeStr = startDate + " 至 " + endDate;

        JSONObject item_first = jsonKeyword( "first" , String.format("【温馨提示】亲爱的家长，%s宝贝的幼儿园有了新的餐饮安排。", childrenName));

        JSONObject item_remark = jsonKeyword("remark", "若有疑问，请及时联系幼儿园！");

        JSONArray arry = new JSONArray();
        arry.add(jsonKeyword("keyword1", className));
        arry.add(jsonKeyword("keyword2", timeStr));
        arry.add(jsonKeyword("keyword3", content));
        arry.add(item_remark);
        arry.add(item_first);

//        String jumpUrl = wxPushLinkUrl + String.format("/#/recipe?date=%s&areaId=%s", startDate, areaId);
        String jumpUrl = wxPushLinkUrl + String.format("/#/pages_sub/recipe/recipe-page?date=%s&areaId=%s", startDate, areaId);

        doWxTemplatePush(templateId, jumpUrl, arry.toString(), childrenId);
    }

    @Override
    @Async
    public void pushPayNotify(String areaId, String childrenId, String childrenName, String teacherName, String orderTitle, String amount, String payType){

        if(StringUtils.isBlank(payType)){
//您好，请尽快完成账单缴费
//学员：张三
//收费项目：补考费
//账单金额：120元
//账单添加日期：2017年4月31日19:00
//如有疑问，请及时联系客服人员

            String content = childrenName + "宝宝的账单缴费成功";
            String templateId = payOrderResultTemplateId;

            JSONObject item_first = jsonKeyword( "first" , content);
            JSONObject item_remark = jsonKeyword("remark", "若有疑问，请及时联系幼儿园！");

            String dateStr = DateUtil.parseToDate(new Date());

            JSONArray arry = new JSONArray();
            arry.add(jsonKeyword("keyword1", childrenName));
            arry.add(jsonKeyword("keyword2", orderTitle));
            arry.add(jsonKeyword("keyword3", amount));
            arry.add(jsonKeyword("keyword4", dateStr));
            arry.add(item_remark);
            arry.add(item_first);

            String jumpUrl = wxPushLinkUrl + "/pages_base/charge/index";

            doWxTemplatePush(templateId, jumpUrl, arry.toString(), childrenId);
        }else{
//在线缴费提醒
//支付结果：支付成功
//收费项目：培训费
//支付方式：微信支付
//支付金额：1000元
//查看订单详情
            String templateId = payOrderNotifyTemplateId;
            String content = "您好，您有新的待缴费账单";

            JSONObject item_first = jsonKeyword( "first" , content);
            JSONObject item_remark = jsonKeyword("remark", "若有疑问，请及时联系幼儿园！");

            JSONArray arry = new JSONArray();
            arry.add(jsonKeyword("keyword1", "支付成功"));
            arry.add(jsonKeyword("keyword2", orderTitle));
            arry.add(jsonKeyword("keyword3", payType));
            arry.add(jsonKeyword("keyword4", amount));
            arry.add(item_remark);
            arry.add(item_first);

            String jumpUrl = wxPushLinkUrl + "/pages_base/charge/index";

            doWxTemplatePush(templateId, jumpUrl, arry.toString(), childrenId);
        }


    }

    @Override
    public void renewPush(String childrenId, String endTime, Integer zaoNum) {

        String today = DateUtil.formatDayToStr(new Date());
        String jumpUrl = wxPushLinkUrl + String.format("/#/renew?date=%s&childrenId=%s", today, childrenId);
        //发送模版id 没看懂作用
        String templateId = renewTemplateId;
        String dateStr = DateUtil.formatDateToStr(new Date());
        Children children = childrenRepository.getOne(childrenId);

        JSONObject item_first = new JSONObject();
        item_first.put("name", "first");
        item_first.put("value", "【温馨提示】您的宝宝需要续费了！");
        item_first.put("color", "#743A3A");

        JSONObject keyword1 = new JSONObject();
        keyword1.put("name", "phrase2");
        keyword1.put("value", children.getName());
        keyword1.put("color", "#743A3A");

        JSONObject keyword2 = new JSONObject();
        keyword2.put("name", "character_string9");
        keyword2.put("value",zaoNum);
        keyword2.put("color", "#743A3A");

//        JSONObject keyword3 = new JSONObject();
//        keyword3.put("name", "time19");
//        keyword3.put("value",endTime);
//        keyword3.put("color", "#743A3A");

        JSONObject item_remark = new JSONObject();
        item_remark.put("name", "remark");
        item_remark.put("value", "若有疑问，请即时联系幼儿园！");
        item_remark.put("color", "#743A3A");
        JSONArray arry = new JSONArray();

        arry.add(keyword1);
        arry.add(keyword2);
//        arry.add(keyword3);
        arry.add(item_remark);
        arry.add(item_first);

        doWxTemplatePush(templateId, jumpUrl, arry.toString(), childrenId);

    }

    @Override
    public void renewPush(String childrenId, Children children) {
        String today = DateUtil.formatDayToStr(new Date());
//        String jumpUrl = wxPushLinkUrl + String.format("/#/renew?date=%s&childrenId=%s", today, childrenId);
//        //发送模版id 没看懂作用
//        String templateId = renewTemplateId;
//        String dateStr = DateUtil.formatDateToStr(new Date());
//
//        JSONObject item_first = new JSONObject();
//        item_first.put("name", "first");
//        item_first.put("value", "【温馨提示】您的宝宝需要续费了！");
//        item_first.put("color", "#743A3A");
//
//        JSONObject keyword1 = new JSONObject();
//        keyword1.put("name", "phrase2");
//        keyword1.put("value", children.getName());
//        keyword1.put("color", "#743A3A");
//
//
//
//        JSONObject keyword2 = new JSONObject();
//        keyword2.put("name", "character_string9");
//        keyword2.put("value",children.getZaoRemainingNum()+ children.getLastZaoNum());
//        keyword2.put("color", "#743A3A");
//
////        JSONObject keyword3 = new JSONObject();
////        keyword3.put("name", "time19");
////        keyword3.put("value",endTime);
////        keyword3.put("color", "#743A3A");
//
//        JSONObject item_remark = new JSONObject();
//        item_remark.put("name", "remark");
//        item_remark.put("value", "若有疑问，请即时联系幼儿园！");
//        item_remark.put("color", "#743A3A");
//        JSONArray arry = new JSONArray();
//
//        arry.add(keyword1);
//        arry.add(keyword2);
////        arry.add(keyword3);
//        arry.add(item_remark);
//        arry.add(item_first);
//
//        doWxTemplatePush(templateId, jumpUrl, arry.toString(), childrenId);
        String jumpUrl = wxPushLinkUrl + String.format("/#/renew?date=%s&childrenId=%s", today, childrenId);
        String templateId = renewTemplateId; // 可用原续费模板ID，也可临时用checkInTemplateId测试
        String dateStr = DateUtil.formatDateToStr(new Date());

        // 1. 构建与入园消息完全一致的JSONArray格式（包含name键，顺序一致）
        // first字段（对应入园消息的item_first）
        JSONObject item_first = new JSONObject();
        item_first.put("name", "first"); // 必须包含"name"键，与入园消息一致
        item_first.put("value", "【温馨提示】您的宝宝需要续费了！");
        item_first.put("color", "#743A3A");

        // 对应入园消息的keyword1（thing1）
        JSONObject keyword1 = new JSONObject();
        keyword1.put("name", "thing1"); // 字段name必须与入园模板的keyword1.name一致
        keyword1.put("value", children.getName());
        keyword1.put("color", "#743A3A");

        // 对应入园消息的keyword2（time2）
        JSONObject keyword2 = new JSONObject();
        keyword2.put("name", "time2"); // 字段name必须与入园模板的keyword2.name一致
        keyword2.put("value", dateStr);
        keyword2.put("color", "#743A3A");

        // 对应入园消息的item_remark
        JSONObject item_remark = new JSONObject();
        item_remark.put("name", "remark"); // 必须包含"name"键，与入园消息一致
        item_remark.put("value", "若有疑问，请即时联系幼儿园！");
        item_remark.put("color", "#743A3A");

        // 2. 数组顺序必须与入园消息完全一致（keyword1 → keyword2 → item_remark → item_first）
        JSONArray arry = new JSONArray();
        arry.add(keyword1);
        arry.add(keyword2);
        arry.add(item_remark);
        arry.add(item_first);

        // 3. 调用推送方法（参数格式与入园消息完全一致）
        doWxTemplatePush(templateId, jumpUrl, arry.toString(), childrenId);
    }

    private String buildParams(String templateId, String jumpUrl, String templateParams){

        JSONObject json = new JSONObject();
        json.put("template_id", templateId);
        json.put("url", jumpUrl);
        json.put("data", templateParams);

        return json.toString();
    }

    @Async
    protected void doWxTemplatePush(String templateId, String jumpUrl, String array, String childrenId) {
        ///send/{channel}/{childrenId}
        String url = wxPostUrl + String.format("/wx/push/send/%s/%s", pushChannel, childrenId);
        try {
            String json = buildParams(templateId, jumpUrl, array);

            log.info("sendStr:" + json);
            String returnStr = HttpClientUtil.sendPostJson(url, json, "UTF-8");
            log.info("returnStr:" + returnStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//    public List<String> buildParams(String templateId, String jumpUrl, String arry, String childrenId,String toUserOpenId) {
//        List<String> paramsList = new ArrayList<>();
//        if(!StringUtils.isBlank(toUserOpenId)){
//            //表示发给特定的某个微信用户，一般是测试用
//            String toUserId =toUserOpenId;
//            JSONObject json = new JSONObject();
//            json.put("touser", toUserId);
//            json.put("template_id", templateId);
//            json.put("url", jumpUrl);
//            json.put("data", arry);
//            paramsList.add(json.toString());
//        }else{
//            //按实际情况发送
//            List<WxUser> toUserList = wxUserService.selectWxUserListByChildrenId(childrenId);
//            System.out.println("toUserList size:" + toUserList.size());
//            for (WxUser toUser : toUserList)
//                if (!StringUtils.isBlank(toUser.getOpenid_wp())) {
//                    String toUserId = toUser.getOpenid_wp();
//                    JSONObject json = new JSONObject();
//                    json.put("touser", toUserId);
//                    json.put("template_id", templateId);
//                    json.put("url", jumpUrl);
//                    json.put("data", arry);
//                    paramsList.add(json.toString());
//                }
//        }
//
//        return paramsList;
//    }
//
//    public void sendToWx(String json) {
//        String url = wxPostUrl +"/wx/push/send";
//        try {
//            log.debug("sendStr:" + json);
//            String returnStr = HttpClientUtil.sendPostJson(url, json.toString(), "UTF-8");
//            log.debug("returnStr:" + returnStr);
//            //JSONObject jsonObject=JSONObject.fromObject(returnStr);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

}
